import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios'

//在main.js中给axios一个全局统一的前缀
// axios.defaults.baseURL='/api'
//因为后端cors解决跨域，因此axious直接请求后端接口即可
axios.defaults.baseURL="http://localhost:9090/"
Vue.prototype.$http=axios

import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
    ak: 'utzxChhKkzG8nauueyLcmWCKhYp62zSQ'
})

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})
// axios前置拦截器:添加请求拦截器，在请求头中加token
// 前端调用后端接口都是通过axios发起请求的，所以在axios调用后端接口之前都会经过axios前置拦截器
// 在访问后端之前会先经过改拦截器，并在拦截器里，给每个请求添加请求头
axios.interceptors.request.use(
    config => {
      // 从localStorage中获取token
      let token = localStorage.getItem("token");

      // 如果token有值,我们就放到请求头里面
      if (token) {
        config.headers["token"] = token;
      }
      return config
    },
    error => {
      return Promise.reject(error)
    })
//响应拦截器，axios的后置拦截器,拦截到后端返回前端的结果是否因为未登录返回
axios.interceptors.response.use(config=>{
    console.log("========")
    let data = config.data;
    //==只判断值不判断类型 ===既判断值又判断类型
    if(!data.success && (400014===data.code)||(400015===data.code))
    {
        localStorage.removeItem("token");
        localStorage.removeItem("loginInfo");
        router.push({ path: '/login' });
    }
    console.log("========")
    return config;
},error => {
    Promise.reject(error)
})

//router的路由拦截器，作用是在前端进行拦截都不会访问后端
// router.beforeEach((to, from, next) => {
//   //NProgress.start();
//   debugger;
//   if (to.path == '/login') {
//     localStorage.removeItem('loginInfo');
//     localStorage.removeItem('token');
//   }
//       let user = JSON.parse(localStorage.getItem('loginInfo'));
//       if (!user && to.path != '/login') {
//           next({ path: '/login' })
//       } else {
//           next()
//       }
// })

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

